import os
import json
from bottle import run, route, template, request, response, redirect, default_app, TEMPLATE_PATH
from beaker.middleware import SessionMiddleware
from app.middlewares.auth_middleware import apply_global_auth_hook
import importlib.util
import sys

# 加载配置
CONFIG = {}
def load_config():
    global CONFIG
    with open('config/config.json', 'r', encoding='utf-8') as f:
        CONFIG = json.load(f)

load_config()

# 自动加载所有控制器
def auto_register_controllers(app):
    controller_dir = 'app/controllers'
    for root, dirs, files in os.walk(controller_dir):
        for file in files:
            if file.endswith('_controller.py'):
                rel_path = os.path.relpath(root, '.').replace(os.sep, '.')
                module_name = f"{rel_path}.{file[:-3]}"  # 去掉 .py

                spec = importlib.util.find_spec(module_name)
                if spec is None:
                    continue

                module = importlib.util.module_from_spec(spec)
                sys.modules[module_name] = module
                spec.loader.exec_module(module)

# 设置模板路径
TEMPLATE_PATH.insert(0, './app/views/')

# 初始化 session
session_opts = {
    'session.type': 'file',
    'session.data_dir': CONFIG['session']['save_path'],
    'session.timeout': CONFIG['session']['timeout'],
    'session.auto': True
}
# 获取 Bottle 实例并注册钩子
bottle_app = default_app()
bottle_app.add_hook('before_request', apply_global_auth_hook())

# 创建中间件应用
app = SessionMiddleware(bottle_app, session_opts)

# 注册控制器
auto_register_controllers(app)

if __name__ == '__main__':
    run(app=app, host='localhost', port=8080, debug=True, reloader=True)